//
//  ProjectViewController.m
//  DaDaBao
//
//  Created by User on 15/8/12.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "RoundProgress.h"
#import "ProjectViewController.h"
#import "DetailViewController.h"
#import "ProjectListModel.h"

@interface ProjectViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)  UITableView *productTableView;
@property (nonatomic, assign)int idx;
@property(nonatomic,strong)  NSMutableArray *productDataSourceArr;
@property(nonatomic,strong) UIButton *noDataBt;
@property(nonatomic,strong)UIButton *tipBt;
@property (nonatomic,assign) int n;

@end

@implementation ProjectViewController

- (void)getHttpData
{
    _n++;
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    _noDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;
    
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1] };
    [AppGlobalClass PostDataWithNSstring:PROJECT_LIST_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [_productTableView.header endRefreshing];
            [_productTableView.footer setState:MJRefreshStateIdle];
            [_productTableView.footer endRefreshing];
            

            if(_idx == 0)
            {
                [_productDataSourceArr removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray objectAtIndex:0];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                self.noDataBt.hidden = TRUE;
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    ProjectListModel *projectListModel = [[ProjectListModel alloc]initWithDictionary:[listArray objectAtIndex:i]];
                    [_productDataSourceArr addObject:projectListModel];
                }
                
                _idx++;
 
                [_productTableView reloadData];
                
                if(listArray.count < 10)
                {
                    [_productTableView.footer noticeNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        _productTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                }
            }
            else
            {
                if (self.productDataSourceArr.count==0) {
                    self.noDataBt.hidden = FALSE;
                    
                }
                
                [self.productTableView.footer noticeNoMoreData];
            }
        }
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        
    } failure:^(NSError *error){
        [self.productDataSourceArr removeAllObjects];
        [self.productTableView reloadData];
        _noDataBt.hidden = FALSE;
        [_productTableView.header endRefreshing];
        [_productTableView.footer setState:MJRefreshStateIdle];
        [_productTableView.footer endRefreshing];
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror){
        [self.productDataSourceArr removeAllObjects];
        [self.productTableView reloadData];
        [_productTableView.header endRefreshing];
        [_productTableView.footer setState:MJRefreshStateIdle];
        [_productTableView.footer endRefreshing];
        _tipBt.hidden = FALSE;
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];
}
//没网提示
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}

- (void)buttonAgainTapped:(id)sender
{
    [_productTableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _idx = 0;
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"项目"];
    [self.view addSubview:topView];
    
    _productDataSourceArr = [[NSMutableArray alloc]init];
    
    if ( _productTableView == nil)
    {
        _productTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT - 113.0f) style:UITableViewStylePlain];
        _productTableView.separatorStyle = UITableViewCellAccessoryNone;
    
        __weak __typeof(self) weakSelf = self;
        
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _productTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheProjectTableView];
        }];
        
         
        // 马上进入刷新状态
        [_productTableView.header beginRefreshing];
        _productTableView.delegate=self;
        _productTableView.dataSource=self;
        _productTableView.sectionHeaderHeight = 0.0f;
        [self.view addSubview:_productTableView];
    }
    
    [_productTableView addSubview:self.noDataBt];
    [_productTableView addSubview:self.tipBt];
}

#pragma mark- tableviewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.productDataSourceArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        UIView *groundView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 100.0f)];
        groundView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:groundView];
        
        UILabel *projectNameLab = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 10.0f, 180.0f, 23.0f)];
        projectNameLab.font = [UIFont boldSystemFontOfSize:16.0f];
        projectNameLab.textColor = [UIColor whiteColor];
        [projectNameLab setTag:100];
        [cell.contentView addSubview:projectNameLab];
        
        UILabel *profitLab = [[UILabel alloc]initWithFrame:CGRectMake(10.0f, 40.0f, 100.0f, 20.0f)];
        profitLab.backgroundColor = [UIColor clearColor];
        profitLab.textColor = RGBA(179.0f, 179.0f, 179.0f, 1.0f);
        profitLab.font = [UIFont boldSystemFontOfSize:15.0f];
        profitLab.text = @"预期收益";
        [cell.contentView addSubview:profitLab];
        
        
        UILabel *timeLimitLab = [[UILabel alloc]initWithFrame:CGRectMake(90.0f * WSCALE, 40.0f, 100.0f, 20.0f)];
        timeLimitLab.backgroundColor = [UIColor clearColor];
        timeLimitLab.textColor = RGBA(179.0f, 179.0f, 179.0f, 1.0f);
        timeLimitLab.font = [UIFont boldSystemFontOfSize:15.0f];
        timeLimitLab.text = @"项目期限";
        [cell.contentView addSubview:timeLimitLab];
        
        UILabel *scaleLab = [[UILabel alloc]initWithFrame:CGRectMake(170.0f * WSCALE, 40.0f, 100.0f, 20.0f)];
        scaleLab.backgroundColor = [UIColor clearColor];
        scaleLab.textColor = RGBA(179.0f, 179.0f, 179.0f, 1.0f);
        scaleLab.font = [UIFont boldSystemFontOfSize:15.0f];
        scaleLab.text = @"项目规模";
        [cell.contentView addSubview:scaleLab];
        
        UILabel *numberProfitLab = [[UILabel alloc]initWithFrame:CGRectMake(10.0f, 65.0f, 100.0f, 20.0f)];
        numberProfitLab.backgroundColor = [UIColor clearColor];
        numberProfitLab.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        numberProfitLab.font = [UIFont systemFontOfSize:19.0f];
        [numberProfitLab setTag:101];
        [cell.contentView addSubview:numberProfitLab];
        
        UILabel *numberTimeLimitLab = [[UILabel alloc]initWithFrame:CGRectMake(90.0f * WSCALE, 65.0f, 100.0f, 20.0f)];
        numberTimeLimitLab.backgroundColor = [UIColor clearColor];
        numberTimeLimitLab.textColor = [UIColor blackColor];
        numberTimeLimitLab.font = [UIFont systemFontOfSize:18.0f];
        [numberTimeLimitLab setTag:102];
        [cell.contentView addSubview:numberTimeLimitLab];
        
        UILabel *numberScaleLab = [[UILabel alloc]initWithFrame:CGRectMake(170.0f * WSCALE, 65.0f, 100.0f, 20.0f)];
        numberScaleLab.backgroundColor = [UIColor clearColor];
        numberScaleLab.textColor = [UIColor blackColor];
        numberScaleLab.font = [UIFont systemFontOfSize:19.0f];
        [numberScaleLab setTag:103];
        [cell.contentView addSubview:numberScaleLab];
        
        RoundProgress * progress = [[RoundProgress alloc]initCreateTheCircleWithFrame:CGRectMake(SCREEN_WIDTH - 85.0f, 12.0f,80.0f, 80.0f) withStartAngle:M_PI*3/2.0 andEndAngle:2.0*M_PI andTheGrayCicleEndAngle:M_PI*3/2.0 +2.0*M_PI ];
        progress.tag = 104;
        progress.progressWidth = 3.0f;
        [cell.contentView addSubview:progress];
        
        UILabel *proLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 85.0f, 40.0f, 80.0f, 20.0f)];
        proLab.textAlignment = NSTextAlignmentCenter;
        proLab.backgroundColor = [UIColor clearColor];
        proLab.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        proLab.font = [UIFont systemFontOfSize:16.0f];;
        [proLab setTag:105];
        [cell.contentView addSubview:proLab];
        
        cell.contentView.backgroundColor = RGBA(230.0f, 230.0f, 230.0f, 1.0f);
    }
    
    ProjectListModel *projectListModel = [_productDataSourceArr objectAtIndex:indexPath.row];
    
    RoundProgress * progress = (RoundProgress *)[cell.contentView viewWithTag:104];
    progress.endAngle = (3 / 2.0f )* M_PI + [projectListModel.progress doubleValue] / [projectListModel.totalCredit doubleValue] * (2 * M_PI);
    [progress setNeedsDisplay];
    
    UILabel *modelProjectNameLab = (UILabel *)[cell.contentView viewWithTag:100];
    modelProjectNameLab.text = [NSString stringWithFormat:@"  %@",projectListModel.productName];
    
    UILabel *modelProfitLab = (UILabel *)[cell.contentView viewWithTag:101];
    modelProfitLab.text = [NSString stringWithFormat:@"%.2f%@",[projectListModel.expectedReturnRatio floatValue], @"%"];;
    
    UILabel *modelNumberTimeLimitLab = (UILabel *)[cell.contentView viewWithTag:102];
    modelNumberTimeLimitLab.text = [NSString stringWithFormat:@"%@天", projectListModel.timeLimit];
    
    UILabel *modelNumberScaleLab = (UILabel *)[cell.contentView viewWithTag:103];
    
    if([projectListModel.totalCredit doubleValue] > 9999)
    {
        modelNumberScaleLab.text = [NSString stringWithFormat:@"%.lf万",[projectListModel.totalCredit doubleValue] /10000.0f];
    }
    else
    {
        modelNumberScaleLab.text = [NSString stringWithFormat:@"%.lf元",[projectListModel.totalCredit doubleValue]];
    }
    
    UILabel *modelProLab = (UILabel *)[cell.contentView viewWithTag:105];
    if ([projectListModel.dueStatus intValue]!=0)
    {
        
        if([projectListModel.saleStatus intValue]!=2)
            
        {
            if([projectListModel.leftCredit intValue] !=0)
            {
                modelProLab.text = [NSString stringWithFormat:@"%.2f%@", [projectListModel.progress doubleValue] * 100 / [projectListModel.totalCredit doubleValue],@"%"];
                modelProjectNameLab.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
            }
            else
            {
                modelProLab.text = @"已投满";
                modelProjectNameLab.backgroundColor = [UIColor lightGrayColor];
            }
        }
        else
        {
            modelProLab.text = @"停售";
            modelProjectNameLab.backgroundColor = [UIColor lightGrayColor];
        }
    }
    else
    {
        modelProLab.text = @"已过期";
        modelProjectNameLab.backgroundColor = [UIColor lightGrayColor];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}
//刷新表
-(void)refreshTheProjectTableView
{
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProjectListModel *projectListModel = [_productDataSourceArr objectAtIndex:indexPath.row];
    
    DetailViewController * vc = [[DetailViewController alloc]initWithProjectID:projectListModel.productId];
    [self.navigationController pushViewController:vc animated:TRUE];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
